var uuidV4 = require('uuid/v4');
var Eventproxy = require('eventproxy');
var logger = require('../common/logger');
var models = require('../models');
var tools = require('../common/tools');
var config = require('config-lite');

exports.newPosition = function newPosition(req, res, next) {
  var ep = new Eventproxy();
  ep.fail(next);

  var user = req.user;
  var data = req.body;

  var positionId = req.params.uuid;

  ep.all('missing', function (attrs) {
    if (attrs.length) {
      return res.send_data({
        code: 400,
        message: '缺少字段' + attrs
      });
    }
  });
  var missingAttrs = tools.checkMissingAttr(data, ['name', 'name_en', 'initial', 'color', 'forbidden_areas', 'allow_areas']);
  if (missingAttrs.length) {
    return ep.emit('missing', missingAttrs);
  }

  data.name = data.name.trim();
  data.name_en = data.name_en.trim();
  data.initial = data.initial.trim();
  var forbidden_areas = data.forbidden_areas;
  var allow_areas = data.allow_areas;

  var sameVal = allow_areas.filter(function(v){ return forbidden_areas.indexOf(v) > -1 });
  if (sameVal.length) {
    return res.send_data({
      code: 400,
      message: '限行区域和可通行区域存在相同值'
    });
  }

  ep.all('createPosition', 'createForbiddens', 'createAllows', function() {
    return res.send_data();
  });

  data.event_uuid = user.event_uuid;

  if (positionId) { // 编辑职务
    models.position_area.destroy({
      where: {
        position_uuid: positionId
      }
    }).then(function() {
      models.position.update(data, {
        where: {
          uuid: positionId
        }
      }).then(function() {
        var forbiddens = forbidden_areas.map(function(area) {
          return {
            position_uuid: positionId,
            area_uuid: area,
            type: 2
          };
        });
        models.position_area.bulkCreate(forbiddens).then(function() {
          ep.emit('createForbiddens');
        });
    
        var allows = allow_areas.map(function(area) {
          return {
            position_uuid: positionId,
            area_uuid: area,
            type: 1
          };
        });
        models.position_area.bulkCreate(allows).then(function() {
          ep.emit('createAllows');
        });
        ep.emit('createPosition');
      });
    });
  } else {
    models.position.create(data).then(function(returnPosition) {
      var positionUUID = returnPosition.uuid;
  
      var forbiddens = forbidden_areas.map(function(area) {
        return {
          position_uuid: positionUUID,
          area_uuid: area,
          type: 2
        };
      });
      models.position_area.bulkCreate(forbiddens).then(function() {
        ep.emit('createForbiddens');
      });
  
      var allows = allow_areas.map(function(area) {
        return {
          position_uuid: positionUUID,
          area_uuid: area,
          type: 1
        };
      });
      models.position_area.bulkCreate(allows).then(function() {
        ep.emit('createAllows');
      });
      ep.emit('createPosition');
    });
  }
};

exports.getPositions = function getPositions(req, res, next) {
  var reqQuery = req.query;
  var page = parseInt(reqQuery.page, 10) || 1;
  page = page > 0 ? page : 1;
  var limit = models.position.pageLimit(Number(reqQuery.limit));
  var offset = models.position.pageOffset(page, limit);

  var condition = {
    offset: offset,
    limit: limit,
    where: {},
    include: [{
      model: models.area,
      through: {
        attributes: ['type'],
        where: {
          type: {
            $in: [1, 2]
          }
        }
      }
    }, {
      as: 'belongto_area',
      model: models.area
    }]
  };

  var user = req.user;
  if (user.event_uuid) {
    condition.where.event_uuid = user.event_uuid;
  }

  models.position.findAndCountAll(condition).then(function(returnPositions) {
    return res.send_data({
      entities: returnPositions.rows,
      total_pages: models.position.totalPages(returnPositions.count, limit),
      current_page: page
    })
  });
};

exports.getPositionByUUID = function getPositionByUUID(req, res) {
  var positionUUID = req.params.uuid;

  models.position.findOne({
    where: {
      uuid: positionUUID
    },
    include: [{
      model: models.area,
      through: {
        attributes: ['type'],
        where: {
          type: {
            $in: [1, 2]
          }
        }
      }
    }]
  }).then(function(returnPosition) {
    return res.send_data({
      entities: returnPosition
    });
  });
};

exports.delPosition = function delPosition(req, res, next) {
  var ep = new Eventproxy();
  ep.fail(next);

  var data = req.body;

  var positionId = req.params.uuid;

  ep.all('delPosition', 'delPositionAreas', function() {
    return res.send_data();
  });

  models.position.destroy({
    where: {
      uuid: positionId
    }
  }).then(function() {
    ep.emit('delPosition');
  });

  models.position_area.destroy({
    where: {
      position_uuid: positionId
    }
  }).then(function() {
    ep.emit('delPositionAreas');
  });
};
